import requests
from .gensecret import genSecret

class FeiShu(object):
    def __init__(self,webhook,secret=None):
        '''
        :param webhook: webhook地址
        :param secret: 签名（可选）
        '''
        self.webhook = webhook
        self.secret = secret
        if self.secret:
            self.gensecret = genSecret(self.secret)

    def sendMessage(self,message:dict,issecret=False) -> bool:
        '''
        发送消息
        :param message: 需要发送的消息，按照飞书官方文档所描述的格式
        :param issecret: 是否需要签名
        :return:
        '''
        if issecret:
            try:
                key,timestamp = self.gensecret.getkey()
            except AttributeError:
                raise Exception('缺少secret')
            auth = {
                'timestamp':timestamp,
                'sign':key
            }
            send_message = self.merge_dicts(auth,message)
        else:
            send_message = message
        res = self.POST(self.webhook,json=send_message)
        return res

    def POST(self,*args,**kwargs):
        '''
        统一请求实例，方便定位问题
        :param args:
        :param kwargs:
        :return:
        '''
        try:
            response = requests.post(*args,**kwargs)
        except requests.exceptions.Timeout:
            raise Exception('消息发送超时')
        except requests.exceptions.ConnectionError:
            raise Exception('网络连接失败')
        try:
            result = response.json()
        except Exception:
            raise Exception('响应异常')
        return result

    def merge_dicts(self,x, y):
        '''
        合并字典
        :param x:
        :param y:
        :return:
        '''
        z = x.copy()
        z.update(y)
        return z

if __name__ == '__main__':

    url = 'https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxxxxxxxxxxxxxxxx'

    c = FeiShu(url,'xxxxxxxxxxxxx')

    message = {
        "msg_type": "text",
        "content": {
            "text": "新更新提醒"
        }
    }

    print(c.sendMessage(message,True))
